﻿<!-- 短信注册 - smsRegister  -->
<template>
  <view>
    <!-- 标题栏 -->
    <view class="head-box ss-m-b-60">
      <view class="head-title ss-m-b-20">注册</view>
      <view class="head-subtitle">请使用本人手机号完成注册</view>
    </view>

    <!-- 表单项 -->
    <uni-forms
      ref="smsRegisterRef"
      v-model="state.model"
      :rules="state.rules"
      validateTrigger="bind"
      labelWidth="140"
      labelAlign="center"
    >
      <uni-forms-item name="mobile" label="手机号">
        <uni-easyinput
          placeholder="请输入手机号"
          v-model="state.model.mobile"
          type="number"
          :inputBorder="false"
        >
          <template v-slot:right>
            <button
              class="ss-reset-button code-btn code-btn-start"
              :disabled="state.isMobileEnd"
              :class="{ 'code-btn-end': state.isMobileEnd }"
              @tap="send()"
            >
              {{ getSmsTimer('smsRegister') }}
            </button>
          </template>
        </uni-easyinput>
      </uni-forms-item>

      <uni-forms-item name="code" label="验证码">
        <uni-easyinput
          placeholder="请输入验证码"
          v-model="state.model.code"
          :inputBorder="false"
          type="number"
          maxlength="4"
        ></uni-easyinput>
      </uni-forms-item>

      <uni-forms-item name="password" label="密码">
        <uni-easyinput
          type="password"
          placeholder="请输入密码"
          v-model="state.model.password"
          :inputBorder="false"
        >
          <template v-slot:right>
            <button class="ss-reset-button login-btn-start" @tap="smsRegisterSubmit"> 注册 </button>
          </template>
        </uni-easyinput>
      </uni-forms-item>
    </uni-forms>

    <button class="ss-reset-button type-btn" @tap="showAuthModal('accountLogin')">
      返回登录
    </button>
  </view>
</template>

<script setup>
  import { computed, ref, reactive, unref } from 'vue';
  import sheep from '@/sheep';
  import { code, mobile, password } from '@/sheep/validate/form';
  import { showAuthModal, closeAuthModal, getSmsCode, getSmsTimer } from '@/sheep/hooks/useModal';
  import {Base64} from 'js-base64'

  const props = defineProps({
    agreeStatus: {
      type: Boolean,
      default: false,
    },
  });

  const smsRegisterRef = ref(null);
  const isLogin = computed(() => sheep.$store('user').isLogin);

  // 数据
  const state = reactive({
    isMobileEnd: false, // 手机号输入完毕
    model: {
      mobile: '', // 手机号
      code: '', // 验证码
      password: '', // 密码
      uuid: '', //uuid
    },
    rules: {
      code,
      mobile,
      password,
    },
  });

  // 3.短信注册
  async function smsRegisterSubmit() {
    const validate = await unref(smsRegisterRef)
      .validate()
      .catch((error) => {
      });
    if (!validate) return;

    if (!props.agreeStatus) {
      sheep.$helper.toast('请勾选同意');
      return;
    }
    
    try {
      state.model.uuid = sheep.$store('user').getUUID();
      
      // 准备注册数据
      const registerData = {
        mobile: state.model.mobile,
        code: state.model.code,
        password: state.model.password,
        uuid: state.model.uuid
      };
      
      // 如果是微信环境，添加微信相关信息
      // #ifdef MP-WEIXIN
      registerData.mpOpenId = uni.getStorageSync('openId');
      // #endif
      
      // #ifdef H5
      // H5环境下的微信授权处理
      let wechatCode = getUrlCode().code;
      if (wechatCode) {
        registerData.wechatCode = wechatCode;
      }
      // #endif
      
      const data = Base64.encode(JSON.stringify(registerData));
      const res = await sheep.$api.user.smsRegister(data);
      
      if (res) {
        closeAuthModal();
        sheep.$helper.toast('注册成功');
        
        // 注册成功后记录登录
        sheep.$api.user.recordLogin();
      }
    } catch (error) {
      sheep.$helper.toast('注册失败，请重试');
    }
  }

  function getUrlCode() {
    // 截取url中的code方法
    var url = location.search;
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
      var str = url.substr(1);
      var strs = str.split("&");
      for (var i = 0; i < strs.length; i++) {
        theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
      }
    }
    return theRequest;
  }

  // 发送验证码
  async function send(){
    if (!state.model.mobile) {
      sheep.$helper.toast('请输入手机号');
      return;
    }
    
    // 验证手机号格式
    if (!/^1[3-9]\d{9}$/.test(state.model.mobile)) {
      sheep.$helper.toast('请输入正确的手机号');
      return;
    }
    
    try {
      const res = await sheep.$api.user.validatePhone(state.model.mobile);
      
      if (res && res.data && res.data.ifSuccess) {
        // 手机号验证通过，发送短信验证码
        getSmsCode('smsRegister', state.model.mobile);
      } else {
        const message = res?.data?.message || '手机号验证失败';
        sheep.$helper.toast(message);
      }
    } catch (error) {
      sheep.$helper.toast('验证失败，请重试');
    }
  }
</script>

<style lang="scss" scoped>
  @import '../index.scss';
</style>
